package com.yss.reportworld.service.impl;

import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yss.common.core.constant.RequestDataHelper;
import com.yss.common.core.enums.YssStatusEnum;
import com.yss.common.core.enums.YssYseNoEnum;
import com.yss.common.core.exception.BusinessException;
import com.yss.common.core.utils.StringUtils;
import com.yss.common.core.utils.uuid.IdUtils;
import com.yss.common.security.utils.SecurityUtils;
import com.yss.reportworld.domain.Table;
import com.yss.reportworld.domain.TableDetail;
import com.yss.reportworld.enums.ReportWorldEnum;
import com.yss.reportworld.mapper.TableDetailMapper;
import com.yss.reportworld.mapper.TableMapper;
import com.yss.reportworld.service.IDescriptionService;
import com.yss.reportworld.util.TableInfoUtil;
import lombok.extern.slf4j.Slf4j;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yss.reportworld.service.IDatabaseDisposeService;
import com.yss.reportworld.mapper.DatabaseDisposeMapper;
import com.yss.reportworld.domain.DatabaseDispose;

/**
 * 基础数据配置信息Service业务层处理
 *
 * @author yss
 * @date 2023-03-31
 */
@Slf4j
@Service
public class DatabaseDisposeServiceImpl extends ServiceImpl<DatabaseDisposeMapper, DatabaseDispose> implements IDatabaseDisposeService {
    @Autowired
    private TableMapper tableMapper;
    @Autowired
    private TableDetailMapper tableDetailMapper;
    @Autowired
    private IDescriptionService descriptionService;

    /**
     * 查询基础数据配置信息列表
     *
     * @param databaseDispose 基础数据配置信息
     * @return 基础数据配置信息
     */
    @Override
    public List<DatabaseDispose> selectDatabaseDisposeList(DatabaseDispose databaseDispose) {
        try {
            TableInfoUtil.handleTableVersion(databaseDispose.getHisVersion()); // 替换表名
            QueryWrapper<DatabaseDispose> wrapper = new QueryWrapper();
            wrapper.orderByDesc("STATUS");
            wrapper.orderByAsc("ORDER_NUM");
            if (StringUtils.isNotEmpty(databaseDispose.getTableName())) {
                wrapper.eq("TABLE_NAME", databaseDispose.getTableName());
            }
            if (null != databaseDispose.getStatus()) {
                wrapper.eq("STATUS", databaseDispose.getStatus());
            }
            if (StringUtils.isNotEmpty(databaseDispose.getProp())) {
                wrapper.like("PROP", databaseDispose.getProp());
            }
            // 导出的时候选择了数据，按照选择的数据
            if (StringUtils.isNotEmpty(databaseDispose.getIds())) {
                List<String> list = JSONArray.parseArray(databaseDispose.getIds(), String.class);
                if (StringUtils.isNotEmpty(list)) {
                    wrapper.in("ID", list);
                }
            }
            return this.list(wrapper);
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

    /**
     * 查询基础数据配置信息
     *
     * @param databaseDispose 基础数据配置信息
     * @return 基础数据配置信息
     */
    @Override
    public DatabaseDispose selectDatabaseDisposeOne(DatabaseDispose databaseDispose) {
        try {
            TableInfoUtil.handleTableVersion(databaseDispose.getHisVersion()); // 替换表名
            return this.getById(databaseDispose.getId());
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

    /**
     * 添加基础数据配置信息
     *
     * @param databaseDispose
     */
    public void addDatabaseDispose(DatabaseDispose databaseDispose) {
        try {
            TableInfoUtil.handleTableVersion(databaseDispose.getHisVersion()); // 替换表名
            databaseDispose.setId(IdUtils.fastSimpleUUID());
            databaseDispose.setCreateBy(SecurityUtils.getUsername());
            databaseDispose.setCreateTime(new Date());
            this.save(databaseDispose);
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

    /**
     * 修改基础数据配置信息
     *
     * @param databaseDispose
     */
    public void editDatabaseDispose(DatabaseDispose databaseDispose) {
        try {
            TableInfoUtil.handleTableVersion(databaseDispose.getHisVersion()); // 替换表名
            databaseDispose.setUpdateTime(new Date());
            databaseDispose.setUpdateBy(SecurityUtils.getUsername());
            this.updateById(databaseDispose);
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

    /**
     * 删除基础数据配置信息
     *
     * @param databaseDispose
     */
    public void delDatabaseDispose(DatabaseDispose databaseDispose) {
        try {
            TableInfoUtil.handleTableVersion(databaseDispose.getHisVersion()); // 替换表名
            QueryWrapper<DatabaseDispose> wrapper = new QueryWrapper();
            wrapper.in("ID", databaseDispose.getIdList());
            this.remove(wrapper);
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

    /**
     * 修改顺序
     *
     * @param list
     */
    public void handleUpdateOrderNum(List<DatabaseDispose> list) {
        try {
            TableInfoUtil.handleTableVersion(list.get(0).getHisVersion()); // 替换表名
            this.updateBatchById(list);
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

    /**
     * 自动生成配置信息
     *
     * @param databaseDispose
     */

    public void initDispose(DatabaseDispose databaseDispose, boolean isCompare) {
        try {
            TableInfoUtil.handleTableVersion(databaseDispose.getHisVersion()); // 替换表名
            String tableName = databaseDispose.getTableName();
            QueryWrapper<DatabaseDispose> wrapper = new QueryWrapper();
            wrapper.eq("TABLE_NAME", tableName);
            // 删除配置信息，重新在库里获取后初始化
            this.remove(wrapper);
            QueryWrapper<Table> wrapperTable = new QueryWrapper();
            wrapperTable.eq("NAME", tableName.replace(ReportWorldEnum.RW_DB_SUFFIX.getCode(), ""));
            Table table = tableMapper.selectOne(wrapperTable);
            if (StringUtils.isNull(table)) {
                throw new BusinessException("没有获取到对应表信息");
            }
            QueryWrapper<TableDetail> detailQueryWrapper = new QueryWrapper<>();
            detailQueryWrapper.eq("TABLE_ID", table.getId());
            detailQueryWrapper.orderByAsc("ORDER_NUM");
            List<TableDetail> detailList = tableDetailMapper.selectList(detailQueryWrapper);
            if (StringUtils.isEmpty(detailList)) {
                throw new BusinessException("没有获取到对应表明细信息");
            }
            List<String> compareKeyList = new ArrayList<>();
            List<String> compareColumnList = new ArrayList<>();
            List<DatabaseDispose> list = new ArrayList<>();
            for (TableDetail detail : detailList) {
                if (StringUtils.isNull(detail)) {
                    continue;
                }
                DatabaseDispose dispose = new DatabaseDispose();
                dispose.setId(IdUtils.fastSimpleUUID());
                dispose.setTableName(tableName);
                dispose.setRequired(2 == detail.getColumnNull() ? 1 : 2); // 不为空的必填
                dispose.setIsShow(1);
                dispose.setWidth(150);
                dispose.setIsQuery(2);
                // 技术主键和业务主键 默认查询条件
                if (YssYseNoEnum.YES.getCode() == detail.getPrimaryKey() || YssYseNoEnum.YES.getCode() == detail.getBusinessPrimaryKey()) {
                    dispose.setIsQuery(1);
                }
                dispose.setStatus(detail.getStatus());
                dispose.setCodeName(detail.getCodeName());
                dispose.setOrderNum(detail.getOrderNum());
                dispose.setIsBusinessPrimary(detail.getBusinessPrimaryKey());
                dispose.setIsPrimary(detail.getPrimaryKey());
                dispose.setProp(detail.getColumnName());
                dispose.setLabel(detail.getColumnChineseName());
                dispose.setComponentType("input");
                dispose.setCreateBy(SecurityUtils.getUsername());
                dispose.setCreateTime(new Date());
                list.add(dispose);
                if (!StringUtils.oneCase(detail.getColumnName().toUpperCase(), ReportWorldEnum.SYS_COLUMN_NAME.getCode())
                        && !StringUtils.oneCase(detail.getColumnName().toUpperCase(), "CREATE_BY,CREATE_TIME,UPDATE_BY,UPDATE_TIME")
                        && 2 == detail.getPrimaryKey() && 2 == detail.getBusinessPrimaryKey()) {
                    compareColumnList.add(detail.getColumnName());
                }
                if (null != detail.getBusinessPrimaryKey() && 1 == detail.getBusinessPrimaryKey()) {
                    compareKeyList.add(detail.getColumnName());
                }
            }
            if (StringUtils.isEmpty(compareKeyList)) {
                throw new BusinessException("没有获取到表的业务主键信息！");
            }
            this.saveBatch(list);
            if (isCompare) {
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("tableName", tableName.replace(ReportWorldEnum.RW_DB_SUFFIX.getCode(), ""));
                map.put("compareKeyList", compareKeyList);
                map.put("compareColumnList", compareColumnList);
                map.put("conditionList", compareKeyList);
                descriptionService.updateCompareconfig(JSONObject.toJSONString(map, SerializerFeature.WriteMapNullValue));
            }
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

}
